package com.airpi.activities;

import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.airpi.R;
import com.airpi.connectivity.RaspberryPiDiscoverer;
import com.airpi.heavy_tasks.AsyncTaskActivity;
import com.airpi.heavy_tasks.AsyncTaskFragment;

/**
 * Login activity handling the authentification of the user by sending a request to the server and retrieving its answer.
 *
 */

public class LoginActivity extends Activity {

	public final static String LOGIN_USER = "user_login";
	public final static String USER_ID = "user_id";
	public final static String USER_STATUS = "user_status";
	public final static String USER_NICKNAME = "user_nickname";
	public final static String USER_PASSWORD = "user_password";

	// Views
	private SharedPreferences sharedPrefs;
	private EditText login;
	private EditText pwd;
	private Button connectButton;
	private CheckBox loginCheckbox;

	/**
	 *Method called on the creation of the Login view which inflates the layout of the activity, handle the call to the correct 
	 * 
	 */

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.login);
		sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		//Retrieve the last IP found in the preferences and tell our futur AsyncTask what's the IP Address 
		String ip = sharedPrefs.getString(RaspberryPiDiscoverer.PREFS_LAST_FOUND, null);
		AsyncTaskFragment.setIP(ip);
		
		//Inflate the different views
		login = (EditText) findViewById(R.id.login_nickname);
		pwd = (EditText) findViewById(R.id.login_password);
		loginCheckbox = (CheckBox) findViewById(R.id.login_checkbox);

		if(loginCheckbox.isChecked()){
			login.setText(sharedPrefs.getString(USER_NICKNAME, null));
			pwd.setText(sharedPrefs.getString(USER_PASSWORD, null));
		}
		connectButton = (Button) findViewById(R.id.login_connect_button);

		//Listener of the Connect Button
		connectButton.setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						try {
							AsyncTaskActivity atc = new AsyncTaskActivity(LoginActivity.this, "Login:"+login.getText().toString()+";"+pwd.getText().toString());
							atc.execute();
							if(atc.get()){
								if(loginCheckbox.isChecked()) { 
									sharedPrefs.edit().putString(USER_NICKNAME, login.getText().toString()).commit();
									sharedPrefs.edit().putString(USER_PASSWORD, pwd.getText().toString()).commit();
								}
								else{
									sharedPrefs.edit().putString(USER_NICKNAME, "").commit();
									sharedPrefs.edit().putString(USER_PASSWORD, "").commit();
								}
								sharedPrefs.edit().putString(LOGIN_USER, login.getText().toString()).commit();

								startActivity(new Intent(LoginActivity.this, MainActivity.class));
								LoginActivity.this.finish();
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						} catch (ExecutionException e) {
							e.printStackTrace();
						}
					}
				});


		pwd.setOnEditorActionListener(
				new OnEditorActionListener(){
					@Override
					public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
						if (pwd.getText().length() >= 4)
						{
							try {
								AsyncTaskActivity atc = new AsyncTaskActivity(LoginActivity.this, "Login:"+login.getText().toString()+";"+pwd.getText().toString());
								atc.execute();
								if(atc.get()){
									sharedPrefs	= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
									sharedPrefs.edit().putString(LOGIN_USER, login.getText().toString()).commit();
									startActivity(new Intent(LoginActivity.this, MainActivity.class));
									LoginActivity.this.finish();
								}
							} catch (InterruptedException e) {
								e.printStackTrace();
							} catch (ExecutionException e) {
								e.printStackTrace();
							}
						}
						return true;
					}
				});

		if (savedInstanceState == null) {
			RaspberryPiDiscoverer rpd = new RaspberryPiDiscoverer(getApplicationContext(),getFragmentManager());
			rpd.execute();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * @param item : The item selected in the Action Bar
	 * Handle the launch of the Settings Activity or Refresh the discovery of the Raspberry of the local network
	 */

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
		case R.id.login_settings:
			startActivity(new Intent(this, ApplicationSettings.class));
			break;

		case R.id.login_menu_refresh_ip:
			RaspberryPiDiscoverer rpd = new RaspberryPiDiscoverer(getApplicationContext(),getFragmentManager());
			rpd.execute();
			break;
		}
		return true;
	}
}